const { src, dest, parallel, series } = require('gulp')
const sass = require('gulp-sass')(require('sass'))
const cleanCSS = require('gulp-clean-css')
const rename = require('gulp-rename')
const cleanDir = require('gulp-clean-dir')
const rollup = require('rollup')
const resolve = require('@rollup/plugin-node-resolve')
const commonjs = require('@rollup/plugin-commonjs')
const PluginVue = require('rollup-plugin-vue')
const babel = require('@rollup/plugin-babel')
const scss = require('rollup-plugin-scss')
const terser = require('@rollup/plugin-terser')

function clearDist(cb) {
  cleanDir('dist')
  cb()
}

function buildScss(cb) {
  src('src/style/index.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(rename({ basename: 'mengyuan-ui' }))
    .pipe(dest('dist'))
    .pipe(
      cleanCSS({ debug: true }, details => {
        console.log(`${details.name}: ${details.stats.originalSize}`)
        console.log(`${details.name}: ${details.stats.minifiedSize}`)
      })
    )
    .pipe(rename({ suffix: '.mini' }))
    .pipe(dest('dist'))
  cb()
}

async function buildJs(cb) {
  const inputOptions = {
    input: 'src/index.js',
    external: ['element-ui', 'vue'],
    plugins: [
      PluginVue(),
      resolve({ extensions: ['.vue', '.js', '.jsx'] }),
      commonjs(),
      babel({ babelHelpers: 'bundled' }),
      scss()
    ]
  }
  const outputOptions = [
    { file: 'dist/mengyuan-ui.esm.js', format: 'esm' },
    { file: 'dist/mengyuan-ui.esm.mini.js', format: 'esm', plugins: [terser()] },
    { file: 'dist/mengyuan-ui.common.js', format: 'umd', name: 'MengyuanUI' },
    { file: 'dist/mengyuan-ui.common.mini.js', format: 'umd', name: 'MengyuanUI', plugins: [terser()] }
  ]
  const bundle = await rollup.rollup(inputOptions)

  Promise.all(outputOptions.map(bundle.write)).then(cb)
}

exports.build = series(clearDist, parallel(buildJs, buildScss))
